import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QMovie
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.uic import *
from PyQt5.QtWidgets import *

from AddClass import AddClass
from ComboBowDialog import ComboBowDialog
from DatabaseInteraction import DatabaseInteraction
from DeleteClass import DeleteClass
from FromCameraDialog import FromCameraDialog
from FromFileDialog import FromFileDialog
from OnlineRecognition import OnlineRecognition
from SetRecognitionRangeForm import SetRecognitionRangeForm

from ui.mainwindow import Ui_MainWindow
import copy
import os

sys.path.append('..')


# 下面这条代码，请根据图形界面平台设定，决定是否要取消
# os.environ["QT_QPA_PLATFORM"] = 'wayland'   #linux中wayland
# os.environ["QT_QPA_PLATFORM"] = 'windows'     #windows
# os.environ["LD_LIBRARY_PATH"]= os.getcwd()+'/Lib/python3.6/site-packages/PyQt5-stubs'     # windows平台
# os.environ["LD_LIBRARY_PATH"]= os.getcwd()+'/lib/python3.6/site-packages/PyQt5-stubs'   # linux平台

class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.database_interaction = DatabaseInteraction()
        self.id_to_class = self.database_interaction.get_id_to_class_dict()

        self.select_index = -1
        self.movie_length = 6
        self.index = 0
        self.player = None
        self.player_list = []
        self.media_list = []
        self.playlist_list = []

        # 界面控件初始化
        self.video_widget_list = []
        self.init_video_widget_list()
        self.select_hint_label = []
        self.init_select_hint_label()
        self.annotation_list = []
        self.init_annotation_list()

        # 数据库初始化
        self.id_list = []
        self.class_list = []
        self.address_list = []
        self.get_all_data_of_database()

        # 初始化多选框
        self.init_class_select_box()

        # 初始化页面跳转按钮
        self.ui.firstPageButton.clicked.connect(self.first)
        self.ui.endPageButton.clicked.connect(self.end)
        self.ui.nextPageButton.clicked.connect(self.next_page)
        self.ui.previousPageButton.clicked.connect(self.previous_page)

        # 初始化查找和删除按钮
        self.ui.inputIndexButton.clicked.connect(self.search)
        self.ui.deleteButton.clicked.connect(self.delete_one_action)

        # 绑定action
        self.ui.actionFromFile.triggered.connect(self.open_from_file_dialog)
        self.ui.classAddAction.triggered.connect(self.add_class)
        self.ui.classDeleteAction.triggered.connect(self.delete_class)
        self.ui.actionFromCamera.triggered.connect(self.open_from_camera_dialog)
        self.ui.actionOnlineRecognition.triggered.connect(self.online_recognition)
        self.ui.actionSetRecognitionRange.triggered.connect(self.set_recognition_range)

        # 刷新
        self.read()

    def init_video_widget_list(self):
        self.video_widget_list.append(self.ui.widget_1)
        self.video_widget_list.append(self.ui.widget_2)
        self.video_widget_list.append(self.ui.widget_3)
        self.video_widget_list.append(self.ui.widget_4)
        self.video_widget_list.append(self.ui.widget_5)
        self.video_widget_list.append(self.ui.widget_6)

        for widget in self.video_widget_list:
            widget.doubleClickedItem.connect(self.widget_clicked)

    def init_select_hint_label(self):
        self.select_hint_label.append(self.ui.locationLabel1)
        self.select_hint_label.append(self.ui.locationLabel2)
        self.select_hint_label.append(self.ui.locationLabel3)
        self.select_hint_label.append(self.ui.locationLabel4)
        self.select_hint_label.append(self.ui.locationLabel5)
        self.select_hint_label.append(self.ui.locationLabel6)

        for i in self.select_hint_label:
            i.setStyleSheet("QLabel{background-color:rgb(200,101,102);}")
            i.setScaledContents(True)
            i.setVisible(False)
            i.lower()

    def init_class_select_box(self):
        for i in self.id_to_class.values():
            self.ui.classSelectBox.addItem(i)
        self.class_sum = len(self.id_to_class.values())

    def init_annotation_list(self):
        self.annotation_list.append(self.ui.classLabel1)
        self.annotation_list.append(self.ui.classLabel2)
        self.annotation_list.append(self.ui.classLabel3)
        self.annotation_list.append(self.ui.classLabel4)
        self.annotation_list.append(self.ui.classLabel5)
        self.annotation_list.append(self.ui.classLabel6)

    # 从数据库中，获取所有数据的id、address、class
    def get_all_data_of_database(self):
        self.id_list, self.address_list, self.class_list, self.dir_list = self.database_interaction.get_all_data()

    # 点击movie，修改select_index+
    def widget_clicked(self):
        sender = self.sender()
        num = int(sender.objectName()[-1])
        self.select_index = num - 1
        self.select()

    # 聚焦选中动画
    def select(self):
        if self.select_index == -1:
            return

        if self.player_list[self.select_index] is None:
            return

        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.player.setPlaylist(self.playlist)
        self.media = self.media_list[self.select_index]
        self.playlist.addMedia(self.media)
        self.player.setVideoOutput(self.ui.widget)
        self.player.setVolume(0)
        self.player.play()

        for i in self.select_hint_label:
            i.setVisible(False)
        self.select_hint_label[self.select_index].setVisible(True)

        self.ui.annotationLabel.setText(self.annotation_list[self.select_index].text())
        self.ui.annotationLabel.setWordWrap(True)

    # 界面跳转至第一页
    def first(self):
        self.index = 0
        self.read()

    # 界面跳转至最后一页面
    def end(self):
        self.index = 999999
        self.read()

    # 界面跳转下一页
    def next_page(self):
        self.index += 6
        self.read()

    # 界面跳转上一页
    def previous_page(self):
        self.index -= 6
        self.read()

    # 根据输入的id查找动画
    def search(self):
        self.index, flag = QInputDialog.getInt(self.ui, "获取下标", "请输入下标", QLineEdit.Normal, 0, len(self.id_list))
        if flag:
            self.read()

    # 刷新
    def read(self):
        self.get_all_data_of_database()
        if self.index > len(self.id_list) - self.movie_length:
            self.index = len(self.id_list) - self.movie_length

        if self.index < 0:
            self.index = 0

        # 释放（release）所有player
        self.player_list.clear()
        self.playlist_list.clear()
        self.media_list.clear()

        for i, widget in enumerate(self.video_widget_list):
            player = QMediaPlayer()
            playlist = QMediaPlaylist()
            self.playlist_list.append(playlist)
            self.player_list.append(player)
            if self.index + i >= len(self.id_list):
                continue

            media = QMediaContent(QUrl.fromLocalFile(self.address_list[self.index + i]))
            self.media_list.append(media)
            playlist.addMedia(media)
            player.setVolume(0)
            player.setPlaylist(playlist)
            player.setVideoOutput(widget)
            player.play()

        for i, annotation_label in enumerate(self.annotation_list):
            if self.index + i >= len(self.id_list):
                continue

            id = self.id_list[self.index + i]
            class_name = self.class_list[self.index + i]
            annotation_label.setText(f"id:{id}\nclass: {class_name}")
            annotation_label.setWordWrap(True)

    def open_from_file_dialog(self):
        self.from_file_dialog = FromFileDialog()
        self.from_file_dialog.exec_()

    def add_class(self):
        self.add_class_dialog = AddClass()
        self.add_class_dialog.exec_()

    def delete_class(self):
        self.delete_class_dialog = DeleteClass()
        self.delete_class_dialog.exec_()

    def open_from_camera_dialog(self):
        from_camera_dialog = FromCameraDialog()
        from_camera_dialog.exec_()
        self.read()

    def delete_one_action(self):
        result = QMessageBox.question(self, '删除确认框', '确定要删除吗', QMessageBox.No, QMessageBox.Yes)
        if result == QMessageBox.Yes:
            id = str(self.id_list[self.index + self.select_index]).zfill(5)
            self.database_interaction.delete_one_data(id)
            self.read()

    def online_recognition(self):
        online_recognition = OnlineRecognition()
        online_recognition.exec_()

    def set_recognition_range(self):
        set_recognition_range = SetRecognitionRangeForm()
        set_recognition_range.exec_()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())
